//
//  Model.m
//  ipersist
//
//  Created by Dan Lorenc on 4/13/09.
//  Copyright 2009 MIT. All rights reserved.
//

#import "Model.h"


@implementation Model
@synthesize dbid, data, defaults;

-(void)save{
	NSMutableArray *table = [[NSMutableArray alloc] initWithArray: [self.defaults objectForKey:[[self class] description]]];
	if (self.dbid != -1){
		[table replaceObjectAtIndex:self.dbid withObject:self.data];
	}
	else{
		[table addObject:self.data];
		self.dbid = [table count];
	}
	[self.defaults setObject:table forKey:[[self class] description]];
	[self.defaults synchronize];
}

-(id)init{
	if (self = [super init]){
		self.defaults = [NSUserDefaults standardUserDefaults];
		self.dbid = -1;
		self.data = [[NSMutableDictionary alloc] init];
	}
	return self;
}
-(void)remove{
	NSMutableArray *table = [self.defaults objectForKey:[[self class] description]];
	
	[table replaceObjectAtIndex:self.dbid withObject:[[NSMutableDictionary alloc] init]];
	[defaults setObject:table forKey:[[self class] description]];
	[table release];
}

+(void)createTable{
	[[NSUserDefaults standardUserDefaults] setObject:[[NSMutableArray alloc] init] forKey:[self description]];
}

+(void)flushTable{
	[self createTable];
}

+(void)deleteTable{
	[[NSUserDefaults standardUserDefaults] removeObjectForKey:[self description]];
}

+(NSMutableArray *)objects{
	NSMutableArray *objects = [[NSUserDefaults standardUserDefaults] objectForKey:[[self class] description]];
	for (NSMutableDictionary *object in objects){
		if ([[object allKeys] count]==0){
			[objects removeObject:object];
		}
	}
	return objects;
}

+(NSMutableArray *)filterObjects:(NSMutableArray *)objects key:(id)key equalsValue:(id)value{
	for (NSMutableDictionary *object in objects){
		if ([object objectForKey:key]!=value){
			[objects removeObject:object];
		}
	}
	return objects;
}
+(NSMutableArray *)filterObjects:(NSMutableArray *)objects key:(id)key lessThanValue:(id)value{
	for (NSMutableDictionary *object in objects){
		if ([object objectForKey:key]>=value){
			[objects removeObject:object];
		}
	}
	return objects;
}
+(NSMutableArray *)filterObjects:(NSMutableArray *)objects key:(id)key greaterThanValue:(id)value{
	for (NSMutableDictionary *object in objects){
		if ([object objectForKey:key]<=value){
			[objects removeObject:object];
		}
	}
	return objects;
}

@end
